package com.songlanyun.interceptor;

import cn.hutool.core.util.ReflectUtil;

import com.songlanyun.common.annotation.DataFilter;
import com.songlanyun.common.utils.RedisKeys;
import com.songlanyun.modules.user.service.SysUserRoleService;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Properties;

/**
 * mybatis数据权限拦截器 - prepare
 *
 * @author ww
 * @date 20202.7.9
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})
})
@Component
public class DataInterceptor implements Interceptor {

    //   @Autowired
    // SysUserRoleService userRoleService;
    @Resource
    RedisTemplate<Object, Object> redisTemplate;

    /**
     * 日志
     */
    private static final Logger log = LoggerFactory.getLogger(DataInterceptor.class);

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        if (invocation.getTarget() instanceof RoutingStatementHandler) {

            RoutingStatementHandler handler = (RoutingStatementHandler) invocation.getTarget();
            StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handler, "delegate");
            //通过反射获取delegate父类BaseStatementHandler的mappedStatement属性
            MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");
            DataFilter permissionAop = getDataFilterByDelegate(mappedStatement);
            if (permissionAop == null) {
                return invocation.proceed();
            }
            //千万不能用下面注释的这个方法，会造成对象丢失，以致转换失败
            //MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            log.info("进入 数据权限拦截器...:" + mappedStatement.getId());

            BoundSql boundSql = delegate.getBoundSql();
            //得到当前uid 对应的角色的数据权限
            String uid = request.getAttribute("uid").toString();

            String fieldStr = "sid";
            //是限制小区数据 ---- 则读取此用户此角色对应的小区id
            StringBuilder sbSql = new StringBuilder(boundSql.getSql());


            //得到此uid 对应的权限，角色
            String str = (String) redisTemplate.opsForValue().get(RedisKeys.getUserDataPrivKey(uid));
            String replace = "";
            if (str != null) {
                replace = str.replace(",", "','");
            }

            sbSql = new StringBuilder("select * from (").append(sbSql).append(" ) s where s." + fieldStr + " in('" + replace + "')");
            log.info("执行SQL: " + sbSql);
            ReflectUtil.setFieldValue(boundSql, "sql", sbSql.toString());
        }
        return invocation.proceed();
    }


    /**
     * 权限sql包装
     *
     * @author ww
     * @date 2020.7.9 上午9:51
     */
    protected String permissionSql(String sql) {
        StringBuilder sbSql = new StringBuilder(sql);

        String premission_param = "regionCd";

        sbSql = new StringBuilder("select * from (").append(sbSql).append(" ) s where s.regionCd like concat(" + "regionCd" + ",'%')  ");

        return sbSql.toString();
    }


    /**
     * 根据 StatementHandler 获取 注解对象
     */
    public DataFilter getDataFilterByDelegate(MappedStatement mappedStatement) {
        DataFilter permissionAop = null;
        try {
            String id = mappedStatement.getId();
            String className = id.substring(0, id.lastIndexOf("."));
            String methodName = id.substring(id.lastIndexOf(".") + 1, id.length());
            final Class cls = Class.forName(className);
            final Method[] method = cls.getMethods();
            for (Method me : method) {
                if (me.getName().equals(methodName) && me.isAnnotationPresent(DataFilter.class)) {
                    permissionAop = me.getAnnotation(DataFilter.class);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return permissionAop;
    }

}